package com.hsck.order.kds.setup

import android.os.Handler
import android.view.LayoutInflater
import androidx.fragment.app.Fragment
import com.hsck.order.kds.R
import com.hsck.order.kds.base.common.setOnSingleClickListener
import com.hsck.order.kds.base.common.setSpannableString
import com.hsck.order.kds.base.isnoam.view.BaseActivity
import com.hsck.order.kds.databinding.ActivityClearingSettingsBinding
import com.hsck.order.kds.setup.fragment.FoodFragment
import com.hsck.order.kds.setup.fragment.GuQingFragment
import java.text.SimpleDateFormat
import java.util.*

class ClearingSettingsActivity : BaseActivity<ActivityClearingSettingsBinding>() {

    private var currentFragment: Fragment? = null

    private val foodFragment = FoodFragment()
    private var guQingFragment = GuQingFragment()

    private val timeFormat = SimpleDateFormat("MM月dd日-HH:mm:ss", Locale.getDefault())
    private val handler = Handler()
    private val runnable: Runnable = object : Runnable {
        override fun run() {
            // 获取当前系统时间并格式化
            val currentTime = timeFormat.format(System.currentTimeMillis())
            // 更新TextView显示的时间
            binding.tvTime.setText(currentTime.replace("-","\n"))
            // 每隔一秒钟更新一次时间
            handler.postDelayed(this, 1000)
        }
    }

    override fun inflateBinding(inflater: LayoutInflater): ActivityClearingSettingsBinding {
        return ActivityClearingSettingsBinding.inflate(inflater)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 移除所有的延时消息和回调，防止内存泄漏
        handler.removeCallbacks(runnable);
    }

    override fun initData() {
        super.initData()
        // 启动定时更新时间的任务
        handler.post(runnable);
        showFragment(foodFragment)
        binding.tvClearingSettingsAll.setOnClickListener {
            binding.tvClearingSettingsAll.setSpannableString(colorId = R.color.white)
            binding.tvClearingSettingsGqcp.setSpannableString(colorId = R.color.grayAE)
            showFragment(foodFragment)
        }
        binding.tvClearingSettingsGqcp.setOnClickListener {
            binding.tvClearingSettingsAll.setSpannableString(colorId = R.color.grayAE)
            binding.tvClearingSettingsGqcp.setSpannableString(colorId = R.color.white)
            showFragment(guQingFragment)
        }
        binding.linHeadBack.setOnSingleClickListener {
            finish()
        }

    }

    private fun showFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        if (!fragment.isAdded) {
            transaction.add(R.id.rl_clearingSettings, fragment)
        }
        currentFragment?.let { transaction.hide(it) }
        transaction.show(fragment)
        transaction.commit()
        currentFragment = fragment
    }


}